package gravitationally_adjustable_physical_ball;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

public class AppPanel extends JPanel implements MouseMotionListener,MouseListener{
    private Ball ball;
    private boolean canDrag=true;
    private boolean inDrag=false;
    private Ceiling ceiling;
    private Ground ground;
    public AppPanel(){
        ceiling=new Ceiling();
        ground=new Ground();
        ball=new Ball();
        addMouseMotionListener(this);
        addMouseListener(this);
        setPreferredSize(new Dimension(800,650));

    }
    public Ball getBall() {
        return ball;
    }

    public double computeDistance(double x1,double y1,double x2,double y2){
        return Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        ground.draw(g);
        ceiling.draw(g);
        ball.paint(g);
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        if (this.canDrag) {
            if (inDrag||computeDistance(e.getX(), e.getY(), ball.getX() + (double) Ball.getDiameter() / 2, ball.getY() + (double) Ball.getDiameter() / 2) <= ((double) Ball.getDiameter()) / 2) {
                if(!(e.getX()>800||e.getX()<0||e.getY()<0||e.getY()>Ground.getY())) {
                    ball.setX(e.getX() - (double) Ball.getDiameter() / 2);
                    ball.setY(e.getY() - (double) Ball.getDiameter() / 2);
                }
                ball.setCanMove(false);
                repaint();
            }
        }
    }

    @Override
    public void mouseMoved(MouseEvent e) {}

    @Override
    public void mouseClicked(MouseEvent e) {}

    @Override
    public void mousePressed(MouseEvent e) {
        if(computeDistance(e.getX(),e.getY(),ball.getX()+ (double) Ball.getDiameter() /2,ball.getY()+ (double) Ball.getDiameter() /2)<=((double)Ball.getDiameter())/2){
            this.canDrag=true;
            this.inDrag=true;
            ball.setX(e.getX() - (double) Ball.getDiameter() / 2);
            ball.setY(e.getY() - (double) Ball.getDiameter() / 2);
            ball.setCanMove(false);
        }
        else {
            this.canDrag=false;
            this.inDrag=false;
            ball.setCanMove(true);
        }
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        this.canDrag=false;
        ball.setCanMove(true);
    }

    @Override
    public void mouseEntered(MouseEvent e) {}

    @Override
    public void mouseExited(MouseEvent e) {}
}
//容纳小球、天花板、地面等对象